#include "HashContainer.h"



HashContainer::Iterator::Iterator(HashContainer & container)
: container(container)
, it(container.data.begin())
{
}
HashContainer::Iterator::~Iterator(){
}
bool HashContainer::Iterator::hasNext() const {
    return it != container.data.end(); 
}
KvPair HashContainer::Iterator::next() {
    KvPair pair(it->first, it->second);
    ++it;
    return pair;
}

std::shared_ptr<IKvContainer::Iterator> HashContainer::iterator() {
    return std::shared_ptr<IKvContainer::Iterator>(new HashContainer::Iterator(*this));
}

const char * HashContainer::get(const int key) const{
    auto it = data.find(key);
    if( it != data.end()){
        return it->second;
    }
    return nullptr;
}
// insert if key not exist 
// replace if key is exist
int HashContainer::put(const int key, const char * value) {
    auto it = data.find(key);
    if( it != data.end()){
        it->second = value;
    }
    else{
        data.insert({key, value});
    }
    return 0;
}

int HashContainer::size() {
    return data.size();
}
int HashContainer::remove(const int key) {
    auto it = data.find(key);
    if( it != data.end()){
        data.erase(it);
    }
    return 0;
}


void HashContainer::test() {
    IKvContainer * kvc = new HashContainer();
    kvc->init();


    kvc->put(1, "hello\0");
    const char * ret = kvc->get(1);
    std::cout << "key(1):" << ret << " size:" << kvc->size() << std::endl;

    auto it = kvc->iterator();
    while(it->hasNext()){
        auto kv = it->next();
        std::cout << kv.getKey() << ":" << kv.getValue() << std::endl;
    }

    kvc->remove(1);

    kvc->deinit(); //Error Check
}
